﻿using System;
using System.IO;
using System.Text;
using System.Xml;

namespace CabConfigProvisioning
{
    public class WspConfigCreator : CabExtract
    {
		protected StringBuilder _sb;
	
		protected FileInfo _configFile;
	
        public WspConfigCreator(FileInfo cabFile, FileInfo configFile) : base(cabFile)
        {
			PathPattern = "^.*\\\\Feature.xml$";
			_bProcessMatching = true;
			_configFile = configFile;
        }

        public WspConfigCreator(string sCabFilePath, string sConfigFilePath) : this(new FileInfo(sCabFilePath), new FileInfo(sConfigFilePath))
        {
        }
        	
     	protected override bool ProcessFile(DecompressedFile file)
        {
        	XmlDocument doc = new XmlDocument();
        	doc.Load(new MemoryStream(file.Content));
        	bool bFound = false;
			XmlNamespaceManager mgr = new XmlNamespaceManager(new NameTable());
			mgr.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/");
			foreach(XmlElement elem in doc.SelectNodes("/sp:Feature/sp:Properties/sp:Property", mgr))
			{
				if(!bFound)
				{
					_sb.AppendFormat("    <file path=\"{0}\">\n", Encoder.EncodeXml(file.Name));
					bFound = true;
				}
				string sKey = elem.Attributes["Key"].Value;
				if(string.IsNullOrEmpty(sKey))
					throw new ArgumentException("Missing key in file '" + file.Name + "'!");
				string sValue = elem.Attributes["Value"].Value;
				_sb.AppendFormat("        <property key=\"{0}\" value=\"{1}\" />\n", Encoder.EncodeXml(sKey), Encoder.EncodeXml(sValue));
			}
			if(bFound)
				_sb.Append("    </file>\n");
            return true;
        }
		
		public override void Execute()
		{
			_sb =  new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n");
			base.Execute();
			_sb.Append("</configuration>\n");
			using(Stream stream = new FileStream(_configFile.FullName, FileMode.Create, FileAccess.Write))
			{
				byte[] buf = Encoding.UTF8.GetBytes(_sb.ToString());
				stream.Write(buf, 0, buf.Length);
			}
            Dispose();
		}
    }
}
